﻿using Xejen.Communication.Configuration;
using Xejen.Communication.Endpoints;
using Xejen.Communication.Http;
using Xejen.Communication.Http.Abstract;
using Xejen.Communication.Http.Communicator;
using Xejen.Communication.Http.Configuration;
using Xejen.Communication.Soap;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace Xejen.Communication.Test
{
    public partial class MainForm : Form
    {
        private readonly IHttpCommunicator _communicator;
        private readonly IConfiguration _configuration;
        public MainForm(IHttpCommunicator communicator, IConfiguration configuration)
        {
            _communicator = communicator;
            _configuration = configuration;

            //以下3种方式均可以注册心跳检测逻辑
            //第1种：
            //communicator.Heartbeat.LocalHeartbeatCheck = () =>
            //{
            //    Debug.WriteLine($"本地心跳检测时间：{DateTime.Now.ToString()}");
            //    byte[] buffer = Guid.NewGuid().ToByteArray();
            //    var value = BitConverter.ToInt64(buffer, 0);

            //    return value % 2 == 1;
            //};
            //communicator.Heartbeat.RemoteHeartbeatCheck = () =>
            //{
            //    Debug.WriteLine($"远端心跳检测时间：{DateTime.Now.ToString()}");
            //    byte[] buffer = Guid.NewGuid().ToByteArray();
            //    var value = BitConverter.ToInt64(buffer, 0);

            //    return value % 2 == 0;
            //};
            //第2种
            //communicator.Heartbeat.RegisterHeartbeatChecker(new HeartbeatChecker());
            //第3种
            communicator.Heartbeat.RegisterHeartbeatChecker<HeartbeatConfig, HeartbeatChecker>();

            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            _communicator.Heartbeat.LocalAliveChanged += (object sender, AliveStatusEventArgs args) =>
            {
                Debug.WriteLine($"设备是否在线：{args.CurrentStatus}");

                Invoke((MethodInvoker)(() =>
                {
                    LocalAliveLabel.Text = args.CurrentStatus.ToString();
                }));
            };
            _communicator.Heartbeat.RemoteAliveChanged += (object sender, AliveStatusEventArgs args) =>
            {
                Debug.WriteLine($"远端是否在线：{args.CurrentStatus}");

                Invoke((MethodInvoker)(() =>
                {
                    RemoteAliveLabel.Text = args.CurrentStatus.ToString();
                }));
            };
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //#region 原始的请求方式，全部api自己构建
            //HttpConfig config = new HttpConfig() { };
            //HttpRequestHandler<HttpClientInvoker, HttpConfig> handle = new HttpRequestHandler<HttpClientInvoker, HttpConfig>();

            //HttpCommunicator<HttpClientInvoker> communicator = new HttpCommunicator<HttpClientInvoker>(config, new HttpClientInvokerCreator(), handle);
            //var result1 = await communicator.RequestAsync(new HttpAddressWrapper
            //{
            //    RequestAddress = new Address<HttpAddress>
            //    {
            //        Value = new HttpAddress
            //        {
            //            Method = HttpMethod.GET,
            //            RequestUri = "https://www.baidu.com/"
            //        }
            //    }
            //});

            //var result2 = await communicator.RequestAsync<string>(new HttpAddressWrapper
            //{
            //    RequestAddress = new Address<HttpAddress>
            //    {
            //        Value = new HttpAddress
            //        {
            //            Method = HttpMethod.GET,
            //            RequestUri = "https://www.baidu.com/"
            //        }
            //    }
            //}, "");

            //var returnData = result2.ToString();
            //#endregion
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            Addresses addresses = new Addresses();
            _configuration.Bind(addresses);

            var result62 = await _communicator.GetAsync(new HttpAddress("https://updater.xejen.com/v1/updater/versions/greater/Xejen.JMark/2024.09.10.00"));


            #region 使用依赖注入的方式构建请求
            HttpResponse result1 = await _communicator.GetAsync(addresses.GetWeatherForecast);
            //var json = result1.ToJson(CommunicationSerializerOptions.Normalize);
            //List<WeatherForecast> weather = result1.Deserialize<List<WeatherForecast>>();

            var result2 = await _communicator.PostAsync(addresses.PostWeatherForecast, new WeatherForecastInputModel
            {
                Date = DateTime.Now,
                Summary = "摘要来喽",
                TemperatureC = 38
            });

            var returnData = result2.DataToString();

            var result3 = await _communicator.PutAsync(new HttpAddress
            {
                RequestUri = addresses.UpdateWeatherForecast.RequestUri,
            }, new WeatherForecastInputModel
            {
                Date = DateTime.Now,
                Summary = "摘要来喽",
                TemperatureC = 38
            });

            var result61 = await _communicator.GetAsync(addresses.GetWeatherForecast);


            var result4 = await _communicator.DeleteAsync(addresses.DeleteWeatherForecast);

            var result5 = await _communicator.PostAsync(addresses.Add, 3);

            var result6 = await _communicator.GetAsync(addresses.RandomInt);

            var result7 = await _communicator.PostAsync(addresses.AddRange, new List<WeatherForecastInputModel>
            {
                new WeatherForecastInputModel
                {
                    Date = DateTime.Now,
                    Summary = "摘要来喽1",
                    TemperatureC = 38
                },
                new WeatherForecastInputModel
                {
                    Date = DateTime.Now,
                    Summary = "摘要来喽2",
                    TemperatureC = 39
                },
                new WeatherForecastInputModel
                {
                    Date = DateTime.Now,
                    Summary = "摘要来喽3",
                    TemperatureC = 40
                }
            });

            var result8 = await _communicator.GetAsync(addresses.RandomForecastArray);

            #endregion
        }

        public class WeatherForecastInputModel
        {
            // 这里可以定义用于 POST 和 PUT 请求的输入模型
            public DateTime Date { get; set; }
            public int TemperatureC { get; set; }
            public string Summary { get; set; }
        }

        public class Addresses
        {
            public HttpAddress GetWeatherForecast { get; set; }
            public HttpAddress PostWeatherForecast { get; set; }
            public HttpAddress UpdateWeatherForecast { get; set; }
            public HttpAddress DeleteWeatherForecast { get; set; }
            public HttpAddress Add { get; set; }
            public HttpAddress RandomInt { get; set; }
            public HttpAddress AddRange { get; set; }
            public HttpAddress RandomForecastArray { get; set; }
        }

        private async void button3_Click(object sender, EventArgs e)
        {
            // 构建请求体参数
            string equipmentCode = "1021-CV-EL-00068";
            string resourceCode = "CV-ZYBH2115";
            string localTime = "2020-01-15T10:10:00";
            string operatorUserID = "EQUtest01";
            string operatorPassword = "1";

            // 构建SOAP请求消息体
            string soapBody = $@"
            <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
                <soap:Header>
                    <LoginSoapHeader xmlns=""http://tempuri.org/"">
                        <EquUserID>EQUtest01</EquUserID>
                        <EquPassword>1</EquPassword>
                        <OperatorUserID>{operatorUserID}</OperatorUserID>
                        <OperatorPassword>{operatorPassword}</OperatorPassword>
                    </LoginSoapHeader>
                </soap:Header>
                <soap:Body>
                    <OperatorLogin xmlns=""http://tempuri.org/"">
                        <model>
                            <EquipmentCode>{equipmentCode}</EquipmentCode>
                            <ResourceCode>{resourceCode}</ResourceCode>
                            <LocalTime>{localTime}</LocalTime>
                            <OperatorUserID>{operatorUserID}</OperatorUserID>
                            <OperatorPassword>{operatorPassword}</OperatorPassword>
                        </model>
                    </OperatorLogin>
                </soap:Body>
            </soap:Envelope>";

            var result2 = await _communicator.PostAsync(new HttpAddress
            {
                RequestUri = "http://122.195.53.162:7008/EquWebService80/EquToMes/EquToMesOperatorLogin.asmx?op=OperatorLogin",
            }, soapBody, new HttpConfig
            {
                Enable = _communicator.Config.Enable,
                ContentType = "text/xml",
                EncodingName = _communicator.Config.EncodingName,
                Timeout = _communicator.Config.Timeout,
                JsonSerializerOptions = _communicator.Config.JsonSerializerOptions,
            });

            var str = result2.ToString();
            SoapResponseParser parser = new SoapResponseParser();
            OperatorLoginResult result = parser.ParseResponse<OperatorLoginResult>(result2.ToString());
        }

        public class OperatorLoginResult
        {
            public int Code { get; set; }
        }

        private async void button6_Click(object sender, EventArgs e)
        {
            //测试通过。注意：XML 声明必须是文档中的第一个节点并且在它之前不允许出现空白字符。
            string soapBody = $@"<?xml version=""1.0"" encoding=""utf-8""?>
            <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
              <soap:Header>
                <LoginSoapHeader xmlns=""http://tempuri.org/"">
                  <EquUserID>admin</EquUserID>
                  <EquPassword>admin123</EquPassword>
                </LoginSoapHeader>
              </soap:Header>
              <soap:Body>
                <HelloWorld xmlns=""http://tempuri.org/"">
                  <body>
                    <EquipmentCode>string</EquipmentCode>
                  </body>
                </HelloWorld>
              </soap:Body>
            </soap:Envelope>";

            var result2 = await _communicator.PostAsync(new HttpAddress
            {
                RequestUri = "http://192.168.3.164:112/WebService1.asmx?op=HelloWorld",
            }, soapBody, new HttpConfig
            {
                Enable = _communicator.Config.Enable,
                ContentType = "text/xml",
                EncodingName = _communicator.Config.EncodingName,
                Timeout = _communicator.Config.Timeout,
                JsonSerializerOptions = _communicator.Config.JsonSerializerOptions,
                //Headers = new System.Collections.Specialized.NameValueCollection
                //{
                //    {"EquUserID","admin" },
                //    {"EquPassword","admin123" },
                //}
            });

            var str = result2.ToString();
            SoapResponseParser parser = new SoapResponseParser();
            MesResult result = parser.ParseResponse<MesResult>(result2.ToString());
        }

        /// <summary>
        /// soap1.2测试成功
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button4_Click(object sender, EventArgs e)
        {
            // 构建请求体参数
            string equipmentCode = "1021-CV-EL-00068";
            string resourceCode = "CV-ZYBH2115";
            string localTime = "2020-01-15T10:10:00";
            string operatorUserID = "EQUtest01";
            string operatorPassword = "1";

            // 构建SOAP请求消息体
            string soapBody = $@"<?xml version=""1.0"" encoding=""utf-8""?>
            <soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope"">
              <soap12:Header>
                <LoginSoapHeader xmlns=""http://tempuri.org/"">
                  <EquUserID>EQUtest01</EquUserID>
                  <EquPassword>1</EquPassword>
                  <OperatorUserID>{operatorUserID}</OperatorUserID>
                  <OperatorPassword>{operatorPassword}</OperatorPassword>
                </LoginSoapHeader>
              </soap12:Header>
              <soap12:Body>
                <OperatorLogin xmlns=""http://tempuri.org/"">
                  <model>
                    <EquipmentCode>{equipmentCode}</EquipmentCode>
                    <ResourceCode>{resourceCode}</ResourceCode>
                    <LocalTime>{localTime}</LocalTime>
                    <OperatorUserID>{operatorUserID}</OperatorUserID>
                    <OperatorPassword>{operatorPassword}</OperatorPassword>
                  </model>
                </OperatorLogin>
              </soap12:Body>
            </soap12:Envelope>";

            var result2 = await _communicator.PostAsync(new HttpAddress
            {
                RequestUri = "http://122.195.53.162:7008/EquWebService80/EquToMes/EquToMesOperatorLogin.asmx?op=OperatorLogin",
            }, soapBody, new HttpConfig
            {
                Enable = _communicator.Config.Enable,
                ContentType = "application/soap+xml",
                EncodingName = _communicator.Config.EncodingName,
                Timeout = _communicator.Config.Timeout,
                JsonSerializerOptions = _communicator.Config.JsonSerializerOptions,
                //Headers = new System.Collections.Specialized.NameValueCollection
                //{
                //    {"EquUserID","EQUtest01" },
                //    {"EquPassword","1" },
                //    {"OperatorUserID","EQUtest01" },
                //    {"OperatorPassword","1" },
                //}
            });

            var str = result2.ToString();
        }

        /// <summary>
        /// 本机的soap1.2成功
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button5_Click(object sender, EventArgs e)
        {
            // SOAP 1.2请求的URL
            string url = "http://192.168.3.164:112/WebService1.asmx?op=HelloWorld";

            // 构建SOAP请求的XML内容
            string soapXml = $@"<?xml version=""1.0"" encoding=""utf-8""?>
            <soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope"">
              <soap12:Header>
                <LoginSoapHeader xmlns=""http://tempuri.org/"">
                  <EquUserID>admin</EquUserID>
                  <EquPassword>admin2</EquPassword>
                </LoginSoapHeader>
              </soap12:Header>
              <soap12:Body>
                <HelloWorld xmlns=""http://tempuri.org/"">
                  <body>
                    <EquipmentCode>string</EquipmentCode>
                  </body>
                </HelloWorld>
              </soap12:Body>
            </soap12:Envelope>";

            // 使用HttpClient发送SOAP请求
            using (HttpClient client = new HttpClient())
            {
                // 发送SOAP请求
                HttpResponseMessage response = await client.PostAsync(url, new StringContent(soapXml, Encoding.UTF8, "application/soap+xml"));

                // 处理响应
                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(result);
                }
                else
                {
                    Console.WriteLine($"HTTP Error: {response.StatusCode} - {response.ReasonPhrase}");
                }
            }

            // 使用HttpClient发送SOAP请求
            using (HttpClient client = new HttpClient())
            {
                // 发送SOAP请求
                HttpResponseMessage response = await client.GetAsync("https://www.baidu.com");

                // 处理响应
                if (response.IsSuccessStatusCode)
                {
                    var dt = response.Headers.Date.Value.LocalDateTime;
                    string result = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(result);
                }
                else
                {
                    Console.WriteLine($"HTTP Error: {response.StatusCode} - {response.ReasonPhrase}");
                }
            }
        }

        class SystemNetTime
        {
            public DateTime SysTime2 { get; set; }
            public string SysTime1 { get; set; }
        }

        private async void button7_Click(object sender, EventArgs e)
        {
            // 构建SOAP请求的XML内容
            string soapBody = $@"<?xml version=""1.0"" encoding=""utf-8""?>
            <soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope"">
              <soap12:Header>
                <LoginSoapHeader xmlns=""http://tempuri.org/"">
                  <EquUserID>admin</EquUserID>
                  <EquPassword>admin123</EquPassword>
                </LoginSoapHeader>
              </soap12:Header>
              <soap12:Body>
                <HelloWorld xmlns=""http://tempuri.org/"">
                  <body>
                    <EquipmentCode>string</EquipmentCode>
                  </body>
                </HelloWorld>
              </soap12:Body>
            </soap12:Envelope>";

            var result2 = await _communicator.PostAsync(new HttpAddress
            {
                RequestUri = "http://192.168.3.164:112/WebService1.asmx?op=HelloWorld",
            }, soapBody, new HttpConfig
            {
                Enable = _communicator.Config.Enable,
                ContentType = "application/soap+xml",
                EncodingName = _communicator.Config.EncodingName,
                Timeout = _communicator.Config.Timeout,
                JsonSerializerOptions = _communicator.Config.JsonSerializerOptions,
                //Headers = new System.Collections.Specialized.NameValueCollection
                //{
                //    {"EquUserID","admin" },
                //    {"EquPassword","admin123" },
                //}
            });

            var str = result2.ToString();
            SoapResponseParser parser = new SoapResponseParser();
            MesResult result = parser.ParseResponse<MesResult>(result2.ToString());
        }

        /// <summary>
        /// 以http post方式调用webservice，成功
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button8_Click(object sender, EventArgs e)
        {
            var result2 = await _communicator.PostAsync(new HttpAddress
            {
                RequestUri = "http://192.168.24.25:15000/WebServiceMesDemo.asmx/addition",
            }, new Dictionary<string, string> { { "i", "21" }, { "j", "34" } }, new HttpConfig
            {
                Enable = _communicator.Config.Enable,
                ContentType = "application/x-www-form-urlencoded",
                EncodingName = _communicator.Config.EncodingName,
                Timeout = _communicator.Config.Timeout,
                JsonSerializerOptions = _communicator.Config.JsonSerializerOptions,
                //Headers = new System.Collections.Specialized.NameValueCollection
                //{
                //    {"EquUserID","admin" },
                //    {"EquPassword","admin123" },
                //}
            });

            var str = result2.ToString();
        }

        /// <summary>
        /// 以http get方式调用webservice，成功
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button9_Click(object sender, EventArgs e)
        {
            var result2 = await _communicator.GetAsync(new HttpAddress
            {
                RequestUri = "http://192.168.24.25:15000/WebServiceMesDemo.asmx/addition?i=22&j=75",
            });

            var str = result2.ToString();
        }
    }

    public class MesResult
    {
        /// <summary>
        /// 执行代码    INT
        /// </summary>
        public int Code { get; set; }
        /// <summary>
        /// 返回信息 STRING
        /// </summary>
        public string Msg { get; set; }
    }
}